import {patchZero} from "@/utils";

export function format(timestamp) {
    const date = new Date(timestamp)
    const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
    const fullDate = `${year}-${patchZero(month)}-${patchZero(day)}`
    const weekIndex = date.getDay()
    return {
        timestamp,
        date: fullDate,
        weekIndex,
        month,
        day: `${patchZero(month)}-${patchZero(day)}`
    }
}


function getBeforeDate(dateStr, num) {
    const result = []
    const oneDay = 1000 * 60 * 60 * 24
    let start = new Date(dateStr).getTime()
    for (let i = 0; i < num; i++) {
        const n = i + 1
        result.push(format(start - (n * oneDay)))
    }
    return result.reverse()
}

function getAfterDate(dateStr, num) {
    const date = new Date(dateStr).getTime()
    const oneDay = 1000 * 60 * 60 * 24
    const result = []
    num += 1
    for (let i = 1; i < num; i++) {
        const item = format(date + (oneDay * i))
        item.isNext = true
        result.push(item)
    }
    return result
}

export function patchCalendar(start, end) {
    let startDate = new Date(start).getTime()
    const endDate = new Date(end).getTime()
    const result = []
    const oneDay = 1000 * 60 * 60 * 24
    let i = startDate
    while (i <= endDate) {
        result.push(format(i))
        i += oneDay
    }
    if (!result.length) return []
    const [firstData] = result
    const endData = result[result.length - 1]
    const beforeNum = firstData.weekIndex
    console.log(beforeNum, 'beforeNum', firstData, 'firstData')
    if (!!beforeNum) {
        result.unshift(...getBeforeDate(firstData.date, beforeNum))
    }
    const endNum = 7 - (endData.weekIndex + 1)
    if (!!endNum) result.push(...getAfterDate(endData.date, endNum))
    return result
}
